/*
    LIBSPELLCHECK Programming Code
    Copyright (C) 2013  Ian Duncan

   This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include "spellcheck.h"

using namespace std;

bool check_spelling(char *dict, char *word)
{
	bool foundword = false;
	string line;
  	ifstream dictionary (dict);
  	if (dictionary.is_open())
  	{
   		while (dictionary.good())
    		{
      		getline (dictionary,line);
      		if(string(word) == line)
		{
			foundword = true;
			break;
		}
		
	
    		}
    		dictionary.close();
 	 }
	else
	{
	 throw 1;
	}

	return foundword;

}

void add_word(char *dict, char *word)
{
	ofstream dictionary;
	dictionary.open(dict, ios::out | ios::app); 
  	if (dictionary.is_open())
  	{
    		dictionary << word;
    		dictionary << "\n";
    		dictionary.close();
 	}
  	else
	{
		throw 1;
	}
  	
}

spelling check_spelling_string(char *dict, string wordList, string sepChar)
{
		
	string word;


	
	//Remove the punctuation from the string before checking
	wordList.erase(
        remove_if ( wordList.begin(), wordList.end(), static_cast<int(*)(int)>(&ispunct) ),
        wordList.end());

	

	istringstream iss (wordList,istringstream::in);

	spelling s;

	s.badWords = 0;

	

      

	while( iss >> word )     
	{

		if(check_spelling(dict, const_cast<char*>(word.c_str())) == false)
		{
			if(s.badList == "")
			{
				s.badList = word;
				s.badWords++;
			}
			else
			{
			s.badList = s.badList + sepChar + word;
			s.badWords++;
			}
		}

	}
	
	

	return s;
}

string correctSpelling(string word, string dict)
{
	const std::string w = word;
	const std::string d = dict;

	SpellCorrector sc;

	sc.load(d);

	return sc.correct(w);

}
			
	

double lib_version()
{
	return 1.20;
}
